package 算法部分.两数相加;

/**
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 *
 * @Author idea
 * @Date created in 8:01 下午 2020/4/17
 */

import java.util.List;

/**
 * Definition for singly-linked list.
 */

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

public class TwoAdd {


    public String twoNumAdd(String num1, String num2) {
        if (num1 == null || num2 == null) {
            throw new RuntimeException("input val is illegal");
        }
        ListNode l1 = this.convert2ListNode(num1);
        ListNode l2 = this.convert2ListNode(num2);
        ListNode result = this.addTwoNumbers(l1, l2);
        StringBuffer stb = new StringBuffer();
        while (result != null) {
            stb.append(result.val);
            result = result.next;
        }
        return stb.reverse().toString();
    }


    private ListNode convert2ListNode(String number) {
        int[] intArr = new int[number.length()];
        for (int i=0 ;i<intArr.length;i++) {
            char ch = number.charAt(i);
            intArr[i]= Integer.parseInt(String.valueOf(ch));
        }
        ListNode listNode = new ListNode(0);
        ListNode curr = listNode;
        for (int i = intArr.length-1; i >= 0; i--) {
            curr.next = new ListNode(intArr[i]);
            curr = curr.next;
        }
        return listNode.next;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode preList = new ListNode(0);
        ListNode curr = preList;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + carry;

            carry = sum / 10;
            sum = sum % 10;
            curr.next = new ListNode(sum);

            curr = curr.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }

        }
        //最后一位的计算需要特殊处理
        if (carry == 1) {
            curr.next = new ListNode(carry);
        }
        return preList.next;
    }

    public static void main(String[] args) {
        TwoAdd ta = new TwoAdd();
        String result = ta.twoNumAdd("0", "9999");
        System.out.println(result);

    }
}
